/*
 * Session.cpp
 * 
 * 会话实现
 */

#include "network/Session.h"
#include <muduo/base/Logging.h>

using namespace muduo;
using namespace muduo::net;

namespace framework {

// 全局会话 ID 生成器
std::atomic<uint64_t> Session::s_sessionIdGenerator_(0);

Session::Session(const TcpConnectionPtr& conn)
    : sessionId_(++s_sessionIdGenerator_),
      conn_(conn),
      state_(SessionState::Connecting),
      lastHeartbeat_(Timestamp::now()) {
    LOG_DEBUG << "Session created: " << sessionId_;
}

Session::~Session() {
    LOG_DEBUG << "Session destroyed: " << sessionId_;
}

TcpConnectionPtr Session::getConnection() const {
    return conn_.lock();
}

void Session::send(const std::string& data) {
    auto conn = getConnection();
    if (conn && conn->connected()) {
        conn->send(data);
    } else {
        LOG_WARN << "Session " << sessionId_ << " send failed: connection invalid";
    }
}

void Session::send(const void* data, size_t len) {
    auto conn = getConnection();
    if (conn && conn->connected()) {
        conn->send(data, len);
    } else {
        LOG_WARN << "Session " << sessionId_ << " send failed: connection invalid";
    }
}

void Session::close() {
    auto conn = getConnection();
    if (conn) {
        conn->shutdown();
    }
}

void Session::forceClose() {
    auto conn = getConnection();
    if (conn) {
        conn->forceClose();
    }
}

void Session::updateHeartbeat() {
    lastHeartbeat_ = Timestamp::now();
}

} // namespace framework

